package com.zhj.agent.resolver;

import com.zhj.agent.support.ClassEnhancePluginDefine;

import net.bytebuddy.description.type.TypeDescription;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * 插件管理器
 */
@Slf4j
public class PluginManager {

    /** 定义插件 */
    private final Map<String, LinkedList<ClassEnhancePluginDefine>> nameMatchDefine = new HashMap<>();


    /**
     * Plugin finder
     *
     * @param classEnhancePluginDefines class enhance plugin defines
     * @since 1.0.0
     */
    public PluginManager(List<ClassEnhancePluginDefine> classEnhancePluginDefines) {
        //遍历插件的名称，并且添加到名字匹配器当中
        classEnhancePluginDefines.forEach(classEnhancePluginDefine -> {
            String enhanceClass = classEnhancePluginDefine.enhanceClass();
            LinkedList<ClassEnhancePluginDefine> enhancePluginDefines = nameMatchDefine.computeIfAbsent(enhanceClass,
                                                                                                        k -> new LinkedList<>());
            enhancePluginDefines.add(classEnhancePluginDefine);
        });
    }


    /**
     * Find
     *
     * @param typeDescription type description
     * @return the list
     * @since 1.0.0
     */
    public List<ClassEnhancePluginDefine> find(TypeDescription typeDescription) {
        List<ClassEnhancePluginDefine> matchedPlugins = new LinkedList<ClassEnhancePluginDefine>();
        String typeName = typeDescription.getTypeName();
        if (nameMatchDefine.containsKey(typeName)) {
            matchedPlugins.addAll(nameMatchDefine.get(typeName));
        }
        return matchedPlugins;
    }

    /**
     * Gets name match define *
     *
     * @return the name match define
     * @since 0.0.1
     */
    public Map<String, LinkedList<ClassEnhancePluginDefine>> getNameMatchDefine() {
        return nameMatchDefine;
    }
}
